package com.hs.service;

import com.hs.config.PageObj;
import com.hs.dao.GoodMapper;
import com.hs.dao.UserGoodMapper;
import com.hs.dao.UserMapper;
import com.hs.entity.Good;
import com.hs.entity.Offer;
import com.hs.entity.User;
import com.hs.entity.UserGood;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserGoodMapper userGoodMapper;
    @Autowired
    GoodMapper goodMapper;
    @Transactional
    public int insertSelective(User record){
        record.setCreateTime(new Date());
        int i = userMapper.insertSelective(record);
        if(i == 0){
            throw new RuntimeException("用户插入失败");
        }
        //初始化用户的物品持有列表
        List<Good> goodList = goodMapper.selectByCondition(null);
        for(Good  g : goodList){
            UserGood userGood  = new UserGood();
            userGood.setUserId(record.getId());
            userGood.setAmount(0);
            userGood.setGoodId(g.getId());
            userGoodMapper.insertSelective(userGood);
            i ++;
        }
        log.info("用户"+record.getName()+"初始化了"+(i - 1)+"物品持有列表");
        return  i;
    };
    public int updateByPrimaryKeySelective(User record){
        return userMapper.updateByPrimaryKeySelective(record);
    };
    public List<User> selectByCondition(User record){
        return userMapper.selectByCondition(record);
    };
    public PageObj page(User item){
        int total = userMapper.selectByConditionCount(item);
        if(total == 0){
            return new PageObj(item.getCurrentPage(), item.getPageSize(),total,null);
        }
        List<User> list = userMapper.selectByCondition(item);
        return new PageObj(item.getCurrentPage(), item.getPageSize(),total,list);
    }

}
